<?php

/**
 * 发送短信
 * @return [type] [description]
 */
function sendSMS($mobile, $content) {
    $url = "http://sms.bechtech.cn/Api/send/data/json?accesskey=" . C('smsAccesskey') . "&secretkey=" . C('smsSecretkey') . "&mobile=" .  $mobile. "&content=".urlencode("您的注册验证码：" . $content . '【见微】');
    $json = smsCurlGet($url);
    $arr = json_decode($json, true); //格式化返回数组
    if($arr['result'] == '01')
        return true;
    else
        //echo '发送失败';
        // echo $arr['result'];
        return false;
}

/**
 * 通过CURL方式获取短信返回信息
 * @param  [type] $url [description]
 * @return [type]      [description]
 */
function smsCurlGet($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $dom = curl_exec($ch);
    curl_close($ch);
    return $dom;
}

/**
 * 生成六位数的验证码
 * @param  integer $length [description]
 * @return [type]          [description]
 */
function generateCode($length = 6) {
    return substr(str_shuffle("012345678901234567890123456789"), 0, $length);
}


function myDate($format,$time){
    if($time){
        return date($format,$time);
    }else{
        return "";
    }
}



function gethttpcurl($url, $ntarr = null, $userToken=''){

    session_start();
    $strCookie = "PHPSESSID=" . $_COOKIE['PHPSESSID'];
    session_write_close();

    $ch=curl_init();

    $header = array('User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1)');
    if($userToken){
        $header[]='USERTOKEN:'.$userToken;
    }
    if($ntarr['timeout']<10) $ntarr['timeout']=10;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_TIMEOUT, (isset($ntarr['timeout']) && is_numeric($ntarr['timeout']))?$ntarr['timeout']:3);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIE, $strCookie);
    if(is_array($ntarr['postarr'])){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $ntarr['postarr']);
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $s = curl_exec($ch);
    curl_close($ch);
    return $s;
}

function getip(){
    return I('server.REMOTE_ADDR');
}


function apigetpost(){
    $string=file_get_contents('php://input');
    $arr=json_decode($string);
    foreach($arr as $k=>$v){
        $_POST[$k]=$v;
    }
}


/**
 * 文件大小单位转换GB MB KB
 * @param  [type] $size [description]
 * @return [type]       [description]
 */
function formatBytes($size) {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
    return round($size, 2).$units[$i];
}

/* function zh2py($str) {
       import('\Common\Util\Pinyin');
       $temp=\Common\Util\Pinyin::GetPinyin($str); //编码为全拼音
       return str_replace(' ', '', $temp);
    }*/
function zh2py($str,$charset="utf-8",$ishead = 0) {
    $restr = '';
    $str = trim($str);
    if($charset=="utf-8"){
        $str=iconv("utf-8","gb2312",$str);
    }
    $slen = strlen($str);
    $pinyins=array();
    if ($slen < 2) {
        return $str;
    }
    $fp = fopen('./Public/pinyin.dat', 'r');
    while (!feof($fp)) {
        $line = trim(fgets($fp));
        $pinyins[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3);
    }
    fclose($fp);

    for ($i = 0; $i < $slen; $i++) {
        if (ord($str[$i]) > 0x80) {
            $c = $str[$i] . $str[$i + 1];
            $i++;
            if (isset($pinyins[$c])) {
                if ($ishead == 0) {
                    $restr .= $pinyins[$c];
                } else {
                    $restr .= $pinyins[$c][0];
                }
            } else {
                $restr .= "_";
            }
        } else if (preg_match("/[a-z0-9]/i", $str[$i])) {
            $restr .= $str[$i];
        } else {
            $restr .= "_";
        }
    }
    return $restr;
}

function setlog($username, $uid, $control, $action, $msg = '', $clienttype = '', $devicename = '', $appversion = '') {
    $model = new \Mapi\Model\LogModel();
    $model->add(array(
        'username' => $username,
        'uid' => $uid,
        'clienttype' => $clienttype ? $clienttype : I('post.clienttype'),
        'devicename' => $devicename ? $devicename : I('post.devicename'),
        'appversion' => $appversion ? $appversion : I('post.appversion'),
        'control' => $control,
        'action' => $action,
        'msg' => $msg,
        'ip' => get_client_ip(),
        'createtime' => time(),
    ));
}

function sock_get($url, $data)
{

    $query_str = http_build_query($data);

    $info = parse_url($url);
    $fp = fsockopen($info["host"], C('HOST_PORT'), $errno, $errstr, 3);
    $head = "GET ".$info['path']."?".$query_str." HTTP/1.0\r\n";
    $head .= "Host: ".$info['host']."\r\n";
    $head .= "\r\n";
    $write = fputs($fp, $head);
    
    // while (!feof($fp))
    // {
    //     $line = fread($fp,4096);
    //       file_put_contents('/var/www/html/push.txt', $line, FILE_APPEND);
    // }
    fclose($fp);
}



function sock_post($url, $query)
{
    $post = http_build_query($query);
    $len = strlen($post);
//发送
    $info = parse_url($url);

    $host = $info['host'];
    $path = $info['path'];
    $fp = fsockopen( $host , C('HOST_PORT'), $errno, $errstr, 30);
    if (!$fp) {
        echo "$errstr ($errno)\n";
    } else {
        $out = "POST $path HTTP/1.1\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Content-Length: $len\r\n";
        $out .= "\r\n";
        $out .= $post . "\r\n";
        // echo($out);
        fwrite($fp, $out);

        //实现异步把下面去掉
        /*while (!feof($fp))
        {
            $line = fread($fp,4096);
            file_put_contents('./push.txt', $line, FILE_APPEND);
        }*/
        //实现异步把上面去掉

        fclose($fp);
    }
}

function callAliyunApi($requestParams) {
    require_once(I('server.DOCUMENT_ROOT') . '/AliyunAPI/' . 'AliyunAPI.php');
    $obj = \AliyunAPI::Obj();
    return $obj->DescribeDomainRecords($requestParams);
}

function callAliyunMtsApi($requestParams) {
    require_once(I('server.DOCUMENT_ROOT') . '/AliyunAPI/' . 'AliyunAPI.php');
    $obj = \AliyunAPI::Obj();
    return $obj->mtsAliCall($requestParams);
}

function  authAliyun($url){
    $url=parse_url($url);
    $time=time()+C('authAliyun_long');
    $rand=rand();
    $key='2nSGzGUytImo';
    $HashValue = md5($url['path']."-".$time."-".$rand."-0-".$key);
    if($url['query']){
        $res=$url['scheme']."://".$url['host'].$url['path'].'?auth_key='.$time."-".$rand."-0-".$HashValue.'&'.$url['query'];
    }else{
        $res=$url['scheme']."://".$url['host'].$url['path'].'?auth_key='.$time."-".$rand."-0-".$HashValue;
    }

    return  $res;
}

/**
 * 操作流
 *
 * @param   $type 1为掐流，2为恢复，3为结束
 * 
 * @return [type] [description]
 */
function liveStatus($type = 1, $id = array(), $status = -1) {
  if($id) {

    switch ($type) {
      case 1:
          foreach($id as $val) {
            $info['Action'] = 'ForbidLiveStream';
            $info['DomainName'] = 'jwlive.appwuhan.com';
            $info['AppName'] = 'jw';
            $info['StreamName'] = $val['stream'];
            $info['LiveStreamType'] = 'publisher';

            $requestid = callAliyunApi($info);
            $requestid = json_decode($requestid, true);
            if($requestid['RequestId'] && count($requestid) == 1) {
              if($status != -1) {
                $map['id'] = $val['id'];
                $res = M('Live')->where($map)->save(array('z_status' => $status)); // 0
              }
            }
          }

        break;
      case 2:
          foreach($id as $val) {
            $info['Action'] = 'ResumeLiveStream';
            $info['DomainName'] = 'jwlive.appwuhan.com';
            $info['AppName'] = 'jw';
            $info['StreamName'] = $val['stream'];
            $info['LiveStreamType'] = 'publisher';

            $requestid = callAliyunApi($info);
            $requestid = json_decode($requestid, true);
            if($requestid['RequestId'] && count($requestid) == 1) {
              if($status != -1) {
                $map['id'] = $val['id'];
                  M('Live')->where($map)->save(array('z_status' => $status)); // 2

              }
            }
          }
        break;

      case 3:
          liveStatus(1, $id, -1);
          foreach($id as $val) {
            $map['id'] = $val['id'];
            if($status != -1) {
              M('Live')->where($map)->save(array('z_status' => $status)); // 3 
            }           
          }      

      default:
        # code...
        break;
    }

    $message['status'] = 0;
    $message['msg'] = '操作成功';

  } else {
    $message['status'] = 1;
    $message['msg'] = '参数不完整';
  }

  return $message;
}

function subWord($str,$len=10,$add="..."){
    if(iconv_strlen($str,'utf8')>10){
        $str=iconv_substr($str,0,$len-iconv_strlen($add,'utf8'),'utf8').$add;
    }

    return $str;
}

function urlsafe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/'),array('-','_'),$data);
    return $data;
}
